package com.arelikebrothers.lottery.data.core.spyder;

import com.arelikebrothers.lottery.data.core.entity.ElevenP5WinCode;
import com.arelikebrothers.lottery.data.core.entity.Province;
import com.arelikebrothers.lottery.data.core.spyder.pip.SqlDbPipeline;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.pipeline.Pipeline;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import java.time.LocalDate;
import java.util.List;

/**
 * Created by lennon on 12/08/2017.
 */
@Component
public class Icaile11P5PageProcessor extends AbstractPageProcessor {

    @Autowired
    private SqlDbPipeline pipeline;

    private String baseUrl = "http://m.sh11x5.icaile.com/kaijiang/";

    @Override
    public void process(Page page) {
        Html html = page.getHtml();

        int size = html.xpath("//div[@class='chart-wrapper']/table/tbody/tr").all().size();
        for (int i = 1; i < size; i++) {
            String trPath = "//div[@class='chart-wrapper']//tbody/tr[" + i + "]";
            String serial = html.xpath(trPath + "/td[1]/text()").toString();
            List<String> all = html.xpath(trPath + "/td[2]/span/text()").all();
            String time = html.xpath(trPath + "/td[3]/text()").toString();

            if (StringUtils.isBlank(serial) || StringUtils.isBlank(time) || all.size() < 5) {
                continue;
            }

            ElevenP5WinCode elevenP5WinCode = new ElevenP5WinCode(serial, all, time);
            elevenP5WinCode.setProvince(getProvince());
            page.putField(serial, elevenP5WinCode);
        }
        Selectable currentDateStr = page.getUrl().regex(".*caile.com/kaijiang/([0-9]{4}-[0-9]{2}-[0-9]{2})");
        LocalDate currentDate = LocalDate.parse(currentDateStr.toString());
        LocalDate prevDate = currentDate.plusDays(1);

        System.out.println("=======Get " + prevDate);
        page.addTargetRequest(baseUrl + prevDate);


    }

    @Override
    public String[] getUrls() {
//        LocalDate now = LocalDate.parse("2013-11-08");
//        LocalDate now = LocalDate.parse("2015-01-09");
//        LocalDate now = LocalDate.parse("2016-12-19");
        // gd
//        LocalDate now = LocalDate.parse("2013-07-19");
//        LocalDate now = LocalDate.parse("2013-08-29");

        // sd
//        LocalDate now = LocalDate.parse("2013-06-20");
//        LocalDate now = LocalDate.parse("2015-07-18");
//        LocalDate now = LocalDate.parse("2016-02-03");
        LocalDate now = LocalDate.parse("2016-08-21");

        String[] urls = new String[]{baseUrl + now};
        return urls;
    }

    @Override
    public Pipeline getPipeLine() {
        return pipeline;
    }

    @Override
    public Province getProvince() {
        return Province.JIANGXI;
    }
}
